package com.firexxx.study.web;

import com.firexxx.study.exception.ParamException;
import com.firexxx.study.util.ExceptionUtil;
import com.firexxx.study.web.response.BusinessError;
import com.firexxx.study.web.response.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.net.BindException;
import java.util.Optional;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/04/09 17:00
 */
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RestResponse exception(Exception ex) {
        log.error("[system exception] ", ex);
        return RestResponse.error(BusinessError.SYSTEM_ERROR);
    }

    @ExceptionHandler(ParamException.class)
    public RestResponse paramException(ParamException ex) {
        log.error("[business exception] param bind error!", ex);
        return RestResponse.error(ex);
    }

    //数据绑定异常
    @ExceptionHandler(BindException.class)
    public RestResponse bindException(BindException ex) {
        log.error("[business exception] param bind error!", ex);

        return RestResponse.error(BusinessError.PARAM_ERROR.getCode(), ExceptionUtil.getFirstNonNullMessage(ex));
    }

    @CrossOrigin

    @ExceptionHandler(value = ConstraintViolationException.class)
    public RestResponse constraintViolationException(ConstraintViolationException ex) {
        Optional<String> messageOptional = ex.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .findFirst();
        if (messageOptional.isPresent()) {
            log.error("[business exception] param bind error!", messageOptional.get());
        } else {
            log.error("[business exception] param bind error!");
        }

        return RestResponse.error(BusinessError.PARAM_ERROR.getCode(), ExceptionUtil.getFirstNonNullMessage(ex));
    }

}